package com.heima.mobile.interceptor;

import com.alibaba.fastjson.JSON;
import com.heima.mobile.thread.TokenThreadUtils;
import com.heima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    private RedisTemplate<String, String> redisTemplate;

    public TokenInterceptor(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. token怎么取？
        // 2. redisTemplate不见了
        String token = request.getHeader("token");

        // 鉴权
        // 1. 获取请求头上的token信息
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("token不能为空");
        }

        // 2. 拿token到redis里面去查
        String userJsonInfo = redisTemplate.opsForValue().get(token);
        // 3. 如果查不到，就返回报错
        if(StringUtils.isEmpty(userJsonInfo)) {
            throw new RuntimeException("token已失效");
        }

        User user = JSON.parseObject(userJsonInfo, User.class);
        if(user == null) {
            throw new RuntimeException("token已失效");
        }

        // 4. 把用户信息写入到ThreadLocal里面
        TokenThreadUtils.setThreadLocal(user);

        System.out.println("token校验成功");
        return true;
    }
}
